package com.example.lte.api;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 *  Excel版本问题：
 *
 * Excel2003版本：后缀是.xls，对应poi的HSSF系，HSSFWorkbook、HSSFSheet……
 *
 * Excel2007版本：后缀是.xlsx，对应poi的XSSF系，XSSFWorkbook、XSSFSheet……
 *
 * 其实，他们都是继承自同一个父类，在定义的时候使用父类（Workbook、Sheet……），把Workbook根据Excel的版本确定了，其他也就跟着确定了。
 *
 * @author lzh
 * @date 2020/11/19 - 17:19
 */
@RestController
@RequestMapping("/excel")
public class ExcelRwController {

    @GetMapping("/downloadPsChargeTemplate")
    public void downloadPsChargeTemplate(HttpServletResponse response) {
        XSSFWorkbook book = new XSSFWorkbook();
        XSSFSheet sheet = book.createSheet("节目集定价模板第1页");
        XSSFRow row = sheet.createRow(0);
        String[] heads = new String[12];
        heads[0] = "ppvCode";
        heads[1] = "epgGroupId";
        heads[2] = "programSetId";
        //设置标题
        for (int k = 0; k < heads.length; k++) {
            row.createCell(k).setCellValue(heads[k]);
            sheet.autoSizeColumn(k, true);
        }
        try {
            String fileName = URLEncoder.encode("节目集定价模板", "UTF8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            OutputStream outputStream = response.getOutputStream();
            //写入输出流
            book.write(outputStream);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
